package com.test.redis.controller;

import com.test.redis.base.Result;
import com.test.redis.dto.BatchAvailabilityRequest;
import com.test.redis.entity.MeetingRoom;
import com.test.redis.service.MeetingRoomService;
import com.test.redis.service.ReservationService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会议室查询控制器
 */
@RestController
@RequestMapping("/api/query")
@Validated
@Slf4j
public class QueryController {
    
    private final ReservationService reservationService;
    private final MeetingRoomService meetingRoomService;
    
    public QueryController(ReservationService reservationService, MeetingRoomService meetingRoomService) {
        this.reservationService = reservationService;
        this.meetingRoomService = meetingRoomService;
    }
    
    /**
     * 批量检查会议室可用性
     */
    @PostMapping("/batch-availability")
    public Result<Map<Long, Boolean>> batchCheckAvailability(
            @RequestBody @Valid BatchAvailabilityRequest request) {
        Map<Long, Boolean> availability = reservationService.batchCheckAvailability(
            request.getRoomIds(), request.getStartTime(), request.getEndTime());
        return Result.success(availability);
    }
    
    /**
     * 查询满足条件的可用会议室
     */
    @GetMapping("/available-rooms")
    public Result<List<MeetingRoom>> findAvailableRooms(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") LocalDateTime startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") LocalDateTime endTime,
            @RequestParam(required = false) Integer minCapacity) {
        
        // 获取所有可用会议室
        List<MeetingRoom> allRooms = meetingRoomService.getAllAvailableRooms();
        
        // 过滤容量
        List<MeetingRoom> capacityFiltered = allRooms;
        if (minCapacity != null) {
            capacityFiltered = allRooms.stream()
                .filter(room -> room.getCapacity() >= minCapacity)
                .collect(Collectors.toList());
        }
        
        // 批量检查可用性
        List<Long> roomIds = capacityFiltered.stream()
            .map(MeetingRoom::getId)
            .collect(Collectors.toList());
        
        Map<Long, Boolean> availability = reservationService.batchCheckAvailability(roomIds, startTime, endTime);
        
        // 返回可用的会议室
        List<MeetingRoom> availableRooms = capacityFiltered.stream()
            .filter(room -> availability.getOrDefault(room.getId(), false))
            .collect(Collectors.toList());
        
        return Result.success(availableRooms);
    }
}

